<template>
    <div class="page">
        <h2 class="page-title">编辑货主合同</h2>

        <div class="form-grid">
            <div class="form-item required">
                <label>合同标题:</label>
                <input v-model="form.contractTitle" placeholder="请输入合同标题" />
            </div>
            <div class="form-item required">
                <label>货主单位:</label>
                <select v-model.number="form.unitId">
                    <option value="">请选择货主单位</option>
                    <option v-for="u in unitOptions" :key="u.id" :value="u.id">{{ u.name }}</option>
                </select>
            </div>
            <div class="form-item required">
                <label>货主负责人:</label>
                <select v-model.number="form.ownerName">
                    <option value="">请选择货主负责人</option>
                    <option v-for="o in ownerOptions" :key="o.id" :value="o.id">{{ o.name }}</option>
                </select>
            </div>
            <div class="form-item required">
                <label>线 路:</label>
                <input v-model="form.route_infoId" placeholder="请输入线路" />
            </div>
            <div class="form-item">
                <label>货 运 价:</label>
                <input v-model.number="form.tonFreightRate" placeholder="请输入吨运价" type="number" step="0.01" />
            </div>

            <div class="form-item">
                <label>包车金额:</label>
                <input v-model.number="form.charterAmount" placeholder="请输入包车金额" type="number" step="0.01" />
            </div>
            <div class="form-item">
                <label>包车条件吨位:</label>
                <input v-model.number="form.charterConditionTonnage" placeholder="请输入包车条件吨位" type="number"
                    step="0.01" />
            </div>
            <div class="form-item required">
                <label>经 办 人:</label>
                <input v-model="form.handler" placeholder="当前登录人" readonly />
            </div>
            <div class="form-item">
                <label>合同金额:</label>
                <input v-model.number="form.contractAmount" placeholder="请输入合同金额" type="number" step="0.01" />
            </div>

            <div class="form-item">
                <label>签订时间:</label>
                <input type="date" v-model="signingDateStr" />
            </div>
        </div>

        <div class="form-block">
            <label>合同标的或项目说明:</label>
            <textarea v-model="form.contractSubjectDescription" rows="4" placeholder="请输入内容" />
        </div>
        <div class="form-block">
            <label>合同主要条款/变更条款:</label>
            <textarea v-model="form.contractTerms" rows="6" placeholder="请输入内容" />
        </div>

        <div class="form-block">
            <label>合同文本（附件）:</label>
            <div class="file-row">
                <input ref="fileInputRef" type="file" @change="onFileChange" />
                <span class="hint">(单个附件最大支持20M，支持: PDF、Word、Excel、Txt格式)</span>
            </div>
            <div v-if="attachmentName" class="file-name">已选择: {{ attachmentName }}</div>
        </div>

        <div class="btn-row">
            <button class="btn primary" :disabled="submitting" @click="submit(1)">提交审批</button>
            <button class="btn" :disabled="submitting" @click="cancel">取消</button>
            <button class="btn success" :disabled="submitting" @click="submit(0)">保存草稿</button>
        </div>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref, computed, onMounted } from 'vue'
import { uploadFile } from '@/utils/fileUpload'
import { useRoute, useRouter } from 'vue-router'
import { write, read } from '@/assets/Axios/axiosHttple'

type Option = { id: number; name: string }

const route = useRoute()
const router = useRouter()
const idParam = Number(route.query.id ?? route.params.id ?? 0)

const form = reactive({
    id: 0,
    contractNumber: '',
    contractTitle: '',
    unitId: undefined as unknown as number | undefined,
    ownerName: undefined as unknown as number | undefined,
    route_infoId: '',
    tonFreightRate: undefined as unknown as number | undefined,
    charterConditionTonnage: undefined as unknown as number | undefined,
    charterAmount: undefined as unknown as number | undefined,
    signingDate: '',
    handler: '',
    contractAmount: undefined as unknown as number | undefined,
    contractSubjectDescription: '',
    contractTerms: '',
    contractAttachment: '',
    processDetail: 0,
    createdAt: '',
    createdBy: ''
})

const signingDateStr = computed({
    get() {
        if (!form.signingDate) return ''
        const d = new Date(form.signingDate)
        if (Number.isNaN(d.getTime())) return ''
        const y = d.getFullYear()
        const m = String(d.getMonth() + 1).padStart(2, '0')
        const day = String(d.getDate()).padStart(2, '0')
        return `${y}-${m}-${day}`
    },
    set(v: string) { form.signingDate = v ? new Date(v).toISOString() : '' }
})

const unitOptions = ref<Option[]>([])
const ownerOptions = ref<Option[]>([])
const fileInputRef = ref<HTMLInputElement | null>(null)
const attachmentName = ref('')
const submitting = ref(false)
const uploadingFile = ref(false)

onMounted(async () => {
    const currentUser = localStorage.getItem('username') || '张三'
    form.handler = currentUser
    await fetchCargoOwners()
    if (Number.isFinite(idParam) && idParam > 0) await loadDetail(idParam)
})

async function fetchCargoOwners() {
    try {
        const res = await read.get('baseinforead/api/CargoOwner/GetCargoOwnerList', { params: { PageIndex: 1, PageSize: 2000, t: Date.now() } })
        const block = res?.data?.data ?? res?.data
        const safe = Array.isArray(block?.data) ? block.data : (Array.isArray(block) ? block : [])
        const unitsMap = new Map<number, string>()
        const owners: Option[] = []
        for (const it of (safe as any[])) {
            const id = Number(it?.id)
            if (!Number.isFinite(id)) continue
            const unitName = it?.unitName ?? it?.company ?? it?.Company ?? it?.UnitName
            const ownerName = it?.ownerName ?? it?.name ?? it?.OwnerName
            if (unitName && !unitsMap.has(id)) unitsMap.set(id, String(unitName))
            if (ownerName) owners.push({ id, name: String(ownerName) })
        }
        unitOptions.value = Array.from(unitsMap.entries()).map(([id, name]) => ({ id, name }))
        ownerOptions.value = owners
    } catch (e) { console.error('获取货主信息失败', e) }
}

async function loadDetail(id: number) {
    try {
        const res = await read.get(`contractmanagementread/api/ContractManagementControllers/GetCargoOwnerById/CargoOwner/${encodeURIComponent(String(id))}`)
        const d = res?.data?.data ?? res?.data
        if (!d) { alert('未找到该记录'); return }
        form.id = d.Id ?? d.id ?? id
        form.contractNumber = d.ContractNumber ?? d.contractNumber ?? ''
        form.contractTitle = d.ContractTitle ?? d.contractTitle ?? ''
        form.unitId = Number(d.UnitId ?? d.unitId ?? d.Unit ?? 0) || undefined
        form.ownerName = Number(d.OwnerId ?? d.ownerId ?? d.Owner ?? 0) || undefined
        form.route_infoId = d.Route ?? d.route ?? d.RouteName ?? ''
        form.tonFreightRate = Number(d.TonFreightRate ?? d.tonFreightRate ?? 0) || undefined
        form.charterConditionTonnage = Number(d.CharterConditionTonnage ?? d.charterConditionTonnage ?? 0) || undefined
        form.charterAmount = Number(d.CharterAmount ?? d.charterAmount ?? 0) || undefined
        form.signingDate = d.SigningDate ?? d.signingDate ?? ''
        form.handler = d.Handler ?? d.handler ?? form.handler
        form.contractAmount = Number(d.ContractAmount ?? d.contractAmount ?? 0) || undefined
        form.contractSubjectDescription = d.ContractSubjectDescription ?? d.contractSubjectDescription ?? ''
        form.contractTerms = d.ContractTerms ?? d.contractTerms ?? ''
        form.contractAttachment = d.ContractAttachment ?? d.contractAttachment ?? ''
        form.processDetail = Number(d.ProcessDetail ?? d.processDetail ?? 0) || 0
        form.createdAt = d.CreatedAt ?? d.createdAt ?? ''
        form.createdBy = d.CreatedBy ?? d.createdBy ?? ''
        const ownerName = d.CargoOwnerContact ?? d.cargoOwnerContact ?? d.OwnerName ?? d.ownerName
        const ownerId = Number(d.OwnerId ?? d.ownerId ?? d.Owner ?? 0) || undefined
        if (ownerName && ownerId) {
            ownerOptions.value = [{ id: ownerId, name: String(ownerName) }]
            form.ownerName = ownerId
            // 确保负责人下拉包含当前负责人名称（如果后端只返回名称或 id 缺失）
            if (ownerName) {
                ownerOptions.value = ownerOptions.value && ownerOptions.value.length > 0 ? ownerOptions.value : [{ id: ownerId || 0, name: String(ownerName) }]
            }
        }
    } catch (e) { console.error('加载详情失败', e) }
}

function cancel() { router.push('/GetCargoOwnerContracts') }

async function onFileChange(e: Event) {
    const input = e.target as HTMLInputElement
    const file = input.files && input.files[0]
    if (!file) return
    attachmentName.value = file.name
    // 异步上传到文件服务；若服务不可达或返回错误，不阻塞提交，回退到使用文件名作为占位
    uploadingFile.value = true
    try {
        try {
            const url = await uploadFile(file)
            if (url) form.contractAttachment = url
            else form.contractAttachment = file.name
        } catch (err: any) {
            console.warn('上传失败，回退为文件名占位', err)
            form.contractAttachment = file.name
        }
    } finally {
        uploadingFile.value = false
        if (fileInputRef.value) fileInputRef.value.value = ''
    }
}

function validate(): boolean {
    if (!form.contractTitle) { alert('请填写合同标题'); return false }
    if (!form.unitId) { alert('请选择货主单位'); return false }
    if (!form.handler) { alert('请填写经办人'); return false }
    return true
}

async function submit(processDetail: number) {
    if (!validate()) return
    submitting.value = true
    try {
        form.processDetail = processDetail
        form.createdAt = new Date().toISOString()
        if (!form.signingDate) form.signingDate = new Date().toISOString()

        const payload: any = { ...form }
        const routeRaw = form.route_infoId
        const maybeNum = Number(routeRaw)
        if (routeRaw !== '' && !Number.isNaN(maybeNum) && String(routeRaw).trim() !== '') {
            payload.route_infoId = maybeNum
            payload.routeName = String(routeRaw ?? '')
        } else {
            payload.route_infoId = 0
            payload.routeName = String(routeRaw ?? '')
        }
        payload.lineName = payload.routeName
        payload.route_name = payload.routeName

        // 尝试多个后端更新接口以兼容不同部署/版本
        // 通过写网关尝试多个更新端点
        const candidates = [
            `contractmanagementwrite/api/ContractManagement/Update/update/${encodeURIComponent(String(idParam))}`,
            `contractmanagementwrite/api/ContractManagement/Update/update`,
            `contractmanagementwrite/api/ContractManagement/UpdateCargoOwner/cargo/update/${encodeURIComponent(String(idParam))}`,
            `contractmanagementwrite/api/ContractManagement/UpdateCargoOwner/cargo/update`,
            `contractmanagementwrite/api/ContractManagement/Update/cargo/update/${encodeURIComponent(String(idParam))}`,
            `contractmanagementwrite/api/ContractManagement/Update/cargo/update`
        ]

        let lastErr: any = null
        for (const url of candidates) {
            try {
                const resp = await write.post(url, payload)
                const d = resp?.data ?? {}
                if (resp.status === 200 && (Number(d?.code) === 200 || d?.data === true || typeof d?.data === 'number' || d?.success === true)) {
                    alert('修改成功')
                    router.push('/GetCargoOwnerContracts')
                    return
                } else {
                    lastErr = { status: resp?.status, body: d }
                }
            } catch (e) { lastErr = e }
        }
        console.error('更新所有候选接口均失败', lastErr)
        alert(`更新失败：${lastErr?.body?.message || lastErr?.message || ''}`)
    } catch (e: any) { console.error(e); alert(e?.message || '网络异常') }
    finally { submitting.value = false }
}
</script>

<style scoped>
.page {
    padding: 16px
}

.page-title {
    font-size: 18px;
    margin: 8px 0 16px
}

.form-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 12px 24px
}

.form-item {
    display: flex;
    align-items: center;
    gap: 8px
}

.form-item>label {
    width: 90px;
    text-align: right;
    color: #333
}

.form-item.required>label::before {
    content: '*';
    color: #f33;
    margin-right: 4px
}

.form-item input,
.form-item select {
    flex: 1;
    height: 32px;
    padding: 4px 8px
}

.form-block {
    margin-top: 12px;
    display: flex;
    flex-direction: column;
    gap: 8px
}

.file-row {
    display: flex;
    align-items: center;
    gap: 12px
}

.hint {
    color: #888;
    font-size: 12px
}

.file-name {
    margin-top: 6px;
    color: #555
}

.btn-row {
    margin-top: 20px;
    display: flex;
    gap: 12px
}

.btn {
    height: 32px;
    padding: 0 14px;
    border: 1px solid #3b82f6;
    color: #3b82f6;
    background: #fff;
    cursor: pointer
}

.btn.primary {
    background: #3b82f6;
    color: #fff
}

.btn.success {
    border-color: #16a34a;
    color: #16a34a
}

.btn:disabled {
    opacity: 0.6;
    cursor: not-allowed
}
</style>
